package com.orangeforms.webadmin.nop;

import cn.dev33.satoken.stp.StpInterface;
import io.nop.api.core.auth.IActionAuthChecker;
import io.nop.api.core.auth.ISecurityContext;
import io.nop.api.core.auth.IUserContext;
import io.nop.commons.util.StringHelper;
import jakarta.inject.Inject;

import java.util.List;

public class SpringActionAuthChecker implements IActionAuthChecker {

    @Inject
    StpInterface stpInterface;

    @Override
    public boolean isPermitted(String permission, ISecurityContext context) {
        IUserContext userContext = context.getUserContext();
        if (userContext == null)
            return false;

        String userId = userContext.getUserId();
        String loginType = "password";

        List<String> perms = stpInterface.getPermissionList(userId, loginType);

        boolean b = perms.contains(permission);
        // 假定写权限总是隐含读权限
        if (!b && permission.endsWith(":query")) {
            String prefix = StringHelper.removeTail(permission, ":query");
            b = perms.contains(prefix + ":mutation");
        }
        return b;
    }
}